const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const path = require('path');
const fs = require('fs');
require('dotenv').config();

const authRoutes = require('./routes/auth'); // 确保导入了 auth 路由
const communityRoutes = require('./routes/community');
const Resource = require('./models/Resource');
const friendRoutes = require('./routes/friends');
const messageRoutes = require('./routes/messages');

const app = express();

// 跨域配置
app.use(cors({
  origin: 'http://localhost:3000', // 确保允许前端的域名
  credentials: true
}));

// 安全中间件
app.use(helmet({
  crossOriginResourcePolicy: { policy: "cross-origin" }
}));

app.use(express.json());

// 速率限制
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100 // 限制每个IP 100个请求
});
app.use('/api/', limiter);

// 路由
app.use('/api/auth', authRoutes);
app.use('/api/challenges', require('./routes/challenges'));
app.use('/api/users', require('./routes/users'));
app.use('/api/community', communityRoutes);

// 配置静态文件服务
app.use('/uploads', express.static(path.join(__dirname, 'public/uploads')));
app.use('/images', express.static(path.join(__dirname, 'public/images')));

// 确保上传目录存在
const uploadDirs = [
  path.join(__dirname, 'public/uploads/posts'),
  path.join(__dirname, 'public/uploads/avatars')
];

uploadDirs.forEach(dir => {
  if (!fs.existsSync(dir)) {
    fs.mkdirSync(dir, { recursive: true });
  }
});

// 路由配置
const resourcesRouter = require('./routes/resources');
app.use('/api/resources', resourcesRouter);

// 注册路由
app.use('/api/friends', friendRoutes);
app.use('/api/messages', messageRoutes);

// 调试中间件 - 添加在路由之前
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
  next();
});

// 调试日志中间件
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next();
});

// 错误处理
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  console.error('错误堆栈:', err.stack);
  res.status(500).json({ 
    message: '服务器内部错误',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 404 处理 - 添加在所有路由之后
app.use('/api/*', (req, res) => {
  console.log('404 Not Found:', req.url);
  res.status(404).json({ message: '未找到请求的资源' });
});

// 启动服务器
const PORT = process.env.PORT || 5001;

// 数据库连接配置
mongoose.connect(process.env.MONGODB_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('MongoDB连接成功');
  // 启动服务器
  app.listen(PORT, () => {
    console.log(`服务器运行在端口 ${PORT}`);
  });
}).catch(err => {
  console.error('MongoDB连接失败:', err);
  process.exit(1); // 如果数据库连接失败，终止程序
});

// 添加连接监控
mongoose.connection.on('connected', () => {
  console.log('Mongoose连接已建立');
});

mongoose.connection.on('error', (err) => {
  console.error('Mongoose连接错误:', err);
});

mongoose.connection.on('disconnected', () => {
  console.log('Mongoose连接已断开');
});

// 优雅关闭连接
process.on('SIGINT', async () => {
  await mongoose.connection.close();
  console.log('Mongoose连接已关闭');
  process.exit(0);
});

// 处理未捕获的Promise异常
process.on('unhandledRejection', (err) => {
  console.error('未处理的Promise异常:', err);
});

// 在现有的数据库连接代码后添加
mongoose.connection.once('open', async () => {
  try {
    const resourceCount = await Resource.countDocuments();
    console.log('数据库连接后的资源数量:', resourceCount);
    
    const resources = await Resource.find();
    console.log('可用资源:', resources.map(r => ({
      title: r.title,
      type: r.type,
      status: r.status
    })));
  } catch (error) {
    console.error('检查资源失败:', error);
  }
}); 